<?php

/**
 * @Author: jack
 * @Date:   2023-11-24 16:31:42
 * @Last Modified by:   jack
 * @Last Modified time: 2023-12-07 09:45:49
 */
namespace App\Http\Controllers\Api;


use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Hash;
use App\Models\AdminUser;
use Gregwar\Captcha\CaptchaBuilder;
use Gregwar\Captcha\PhraseBuilder;
use Illuminate\Support\Str;
use App\Rules\Captcha;

class LoginController extends Controller
{
    public function login(Request $request){
        $rules = [
            'username' => 'required',
            'password' => 'required',
            'code_key' => 'required',
            // 'school_id' => 'required',
            'code' => [
                'required',
                new Captcha
            ]
        ];
// var_dump(($request->captcha_token));
// var_dump(cache($request->captcha_token));
        $validator = \Validator::make($request->all(), $rules, [
            'username.required' => '账户必须填写',
            'password.required' => '密码必须填写',
            // 'school_id.required' => '请选择学校',
            'required' => '参数必须填写',
        ]);
        if ($validator->fails()) {
            return $this->error($validator->errors()->first());
        }

        $user = AdminUser::where('username', $request->username)->first();

        if (! $user || ! Hash::check($request->password, $user->password)) {
            return $this->error('用户不存在或者密码错误');
        }
        if($user->status != 1) {
            return $this->error('用户已经禁用，请联系管理员');
        }
        $user->updated_at = now();
        $user->save();
        $token = $user->createToken($request->username)->plainTextToken;
        return $this->success(compact('user', 'token'));
    }

    public function captcha(Request $request){
        $phraseBuilder = new PhraseBuilder(4);
// print_r(gd_info());dd(1);
        $builder = new CaptchaBuilder(null, $phraseBuilder);
        $builder->build($width = 100, $height = 40,$font = null);
        $phrase = $builder->getPhrase();
        $token = Str::random(20);
        // var_dump($phrase);
        cache([$token=> $phrase], 500);
        return $this->success(['token'=> $token, 'image'=> $builder->inline(90)]);
    }
}
